<template>
    <div class="dashboard-viewer-container">
        <!-- 仪表板标题和描述 -->
        <div class="dashboard-header">
            <h1 class="dashboard-title">{{ dashboardData.name || 'Dashboard' }}</h1>
            <p class="dashboard-description">{{ dashboardData.description || '' }}</p>
        </div>

        <!-- 图表区域 -->
        <div class="charts-container">
            <el-row :gutter="20">
                <!-- 图表 -->
                <el-col
                    v-for="(chart, index) in dashboardData.charts"
                    :key="index"
                    :span="12">
                    <div class="chart-card">
                        <div class="chart-title">
                            <span>{{ chart.title }}</span>
                        </div>
                        <div class="chart-container" :id="`dashboard-chart-${index}`"></div>
                    </div>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getDashboardDetail } from '@/api/dashboard-manage'
import {
    getAnalysisData,
    getProductAnalysis,
    getCustomerAnalysis,
    getShopAnalysis,
    getIncomeAnalysis
} from '@/api/analysis'

const route = useRoute()
const dashboardData = ref({
    name: '',
    description: '',
    charts: []
})
const chartInstances = ref([])

// 使用 computed 计算仪表板ID
const dashboardId = computed(() => {
    return route.params.id
})

// 加载仪表板数据
const loadDashboard = async () => {
    try {
        console.log('仪表板ID:', dashboardId.value)
        const response = await getDashboardDetail(dashboardId.value)
        console.log('加载到的仪表板数据:', response)
        dashboardData.value = response

        // 清除旧的图表实例
        chartInstances.value.forEach(instance => {
            if (instance) {
                instance.dispose()
            }
        })
        chartInstances.value = []

        // 加载图表数据
        nextTick(() => {
            loadAllCharts()
        })
    } catch (error) {
        ElMessage.error('Failed to load dashboard: ' + error.message)
    }
}

// 添加这个监听器，当路由参数变化时重新加载仪表板数据
watch(() => route.params.id, (newId, oldId) => {
    if (newId && newId !== oldId) {
        loadDashboard()
    }
}, { immediate: true })

// 加载所有图表
const loadAllCharts = async () => {
    if (!dashboardData.value.charts || dashboardData.value.charts.length === 0) {
        return
    }
    
    try {
        // 收集所有图表的数据请求
        const chartDataPromises = dashboardData.value.charts.map((chart) => {
            return fetchChartData(chart)
        })
        
        // 并行请求所有图表数据
        const chartDataResults = await Promise.all(chartDataPromises)
        
        // 使用返回的数据渲染所有图表
        chartDataResults.forEach((result, index) => {
            renderChart(index, result)
        })
    } catch (error) {
        ElMessage.error('Failed to load chart data: ' + error.message)
    }
}

// 为单个图表获取数据
const fetchChartData = async (chart) => {
    if (!chart) return null
    
    // 解析数据源配置
    const dataSourceConfig = JSON.parse(chart.dataSource)
    const dataSourceType = dataSourceConfig.type
    
    console.log('正在请求数据源:', dataSourceType)
    
    // 准备查询参数
    const queryParams = {
        startDate: '2023-01-01',
        endDate: '2023-12-31'
    }
    
    let responseData
    
    // 根据数据源类型调用不同的API
    switch (dataSourceType) {
        // 核心分析数据
        case 'totalSalesProfit':
        case 'orderCount':
        case 'salesVolume':
        case 'customerCount':
            responseData = await getAnalysisData('core', queryParams)
            break
            
        // 产品分析数据
        case 'productCategorySales':
        case 'productUnitPriceProfit':
        case 'productCategorySalesVolume':
        case 'productCategorySalesDate':
            queryParams.category = 'Accessories'
            responseData = await getProductAnalysis(queryParams)
            break
            
        case 'productCategoryDistribution':
            queryParams.category = null
            responseData = await getProductAnalysis(queryParams)
            break
            
        // 客户分析数据
        case 'consumptionPerCapita':
        case 'customerTimePreference':
        case 'customerCityDistribution':
        case 'ageDistribution':
            queryParams.category = null
            responseData = await getCustomerAnalysis(queryParams)
            break
            
        // 商店分析数据
        case 'shopSalesProfit':
            queryParams.category = null
            queryParams.shopId = 21
            responseData = await getShopAnalysis(queryParams)
            break
        case 'shopDistribution':
            const obj = {
                "startDate": null,
                "endDate": null,
                "category": null,
                "city": null,
                "shopId": null,
                "operator": null,
                "amount": null
            }
            responseData = await getShopAnalysis(obj)
            break
            
        // 收入分析数据
        case 'cumulativeSalesProfit':
        case 'monthlySalesProfit':
            responseData = await getIncomeAnalysis(queryParams)
            break
            
        default:
            throw new Error('不支持的数据源类型')
    }
    
    // 提取图表数据
    return extractChartData(dataSourceType, responseData, chart.type)
}

// 从API响应中提取图表数据
const extractChartData = (dataSourceType, responseData, chartType) => {
    if (!responseData) return null
    
    switch (dataSourceType) {
        case 'totalSalesProfit':
            return {
                color: ['#409EFF', '#67C23A'],
                legend: {
                    data: ['Total Sales', 'Profit'],
                },
                xAxis: responseData.chartData?.months,
                series: [
                    {
                        name: 'Total Sales',
                        type: chartType,
                        data: responseData.chartData?.sales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.chartData?.profits
                    }
                ]
            };

        case 'orderCount':
            return {
                color: ['#F56C6C'],
                legend: {
                    data: ['Order Count'],
                },
                xAxis: responseData.chartData?.months,
                series: [
                    {
                        name: 'Order Count',
                        type: chartType,
                        data: responseData.chartData?.orders
                    }
                ]
            };

        case 'salesVolume':
            return {
                color: ['#E6A23C'],
                legend: {
                    data: ['Sales Volume'],
                },
                xAxis: responseData.chartData?.months,
                series: [
                    {
                        name: 'Sales Volume',
                        type: chartType,
                        data: responseData.chartData?.volumes
                    }
                ]
            };

        case 'customerCount':
            return {
                color: ['#909399'],
                legend: {
                    data: ['Customer Count'],
                },
                xAxis: responseData.chartData?.months,
                series: [
                    {
                        name: 'Customer Count',
                        type: chartType,
                        data: responseData.chartData?.customers
                    }
                ]
            };

        // 产品分析相关图表
        case 'productCategorySales':
            return {
                color: ['#67C23A'],
                legend: {
                    data: ['Category Sales'],
                },
                xAxis: responseData.productShares?.map(item => item.category),
                series: [
                    {
                        name: 'Category Sales',
                        type: chartType,
                        data: responseData.productShares?.map(item => item.salesAmount)
                    }
                ]
            };
            
        case 'productCategoryDistribution':
            return {
                series: responseData.productShares?.map(item => ({
                    name: item.category,
                    value: item.salesAmount,
                    percentage: item.percentage
                }))
            }
            
        case 'customerCityDistribution':
            return {
                series: responseData.distribution?.city
            }
            
        case 'shopDistribution':
            return {
                series: responseData.cityData?.distribution || 
                       responseData.rankingData?.shopRanking?.map(shop => ({
                           name: `店铺${shop.shopId}`,
                           value: shop.sales || 0
                       }))
            }
            
        case 'cumulativeSalesProfit':
        case 'monthlySalesProfit':
            return {
                legend: {
                    data: ['Sales', 'Profit']
                },
                xAxis: responseData.chartData?.months,
                series: [
                    {
                        name: 'Sales',
                        type: chartType,
                        data: responseData.chartData?.monthSales
                    },
                    {
                        name: 'Profit',
                        type: chartType,
                        data: responseData.chartData?.monthProfits
                    }
                ]
            }

        // 默认返回示例数据
        default:
            return {
                xAxis: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
                series: [{
                    name: '示例数据',
                    type: chartType,
                    data: [120, 200, 150, 80, 70, 110, 130]
                }]
            };
    }
};

// 渲染图表
const renderChart = (index, data) => {
    if (!data) return
    
    const chart = dashboardData.value.charts[index]
    const chartType = chart.type
    const dataSourceConfig = JSON.parse(chart.dataSource)
    const dataSourceType = dataSourceConfig.type
    
    // 初始化ECharts实例
    const chartContainer = document.getElementById(`dashboard-chart-${index}`)
    if (!chartContainer) return
    
    // 清除旧实例
    if (chartInstances.value[index]) {
        chartInstances.value[index].dispose()
    }
    
    const chartInstance = echarts.init(chartContainer)
    
    // 根据图表类型处理数据格式
    let option = {}
    
    switch (chartType) {
        case 'line':
        case 'bar':
        case 'area':
            option = {
                tooltip: { trigger: 'axis' },
                legend: data.legend || {},
                color: data.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                grid: {
                    left: '3%',
                    right: '4%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.xAxis || data.months || [],
                    axisLabel: {
                        rotate: 45
                    }
                },
                yAxis: { type: 'value' },
                series: data.series ? data.series.map(series => {
                    if (chartType === 'area') {
                        return { ...series, type: 'line', areaStyle: {} }
                    }
                    return series
                }) : []
            }
            break

        case 'pie':
        case 'ring':
            // 检查是否为特殊格式的系列配置（已经包含完整的系列配置）
            if (data.series && Array.isArray(data.series) && data.series[0] && data.series[0].type) {
                // 直接使用提供的系列配置
                option = {
                    tooltip: { trigger: 'item' },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        type: 'scroll',
                        show: false
                    },
                    color: data.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                    series: data.series
                }
            } else {
                // 常规数据数组格式
                option = {
                    tooltip: { trigger: 'item' },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        type: 'scroll',
                        show: false
                    },
                    color: data.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                    series: [{
                        name: chart.title,
                        type: 'pie',
                        radius: chartType === 'ring' ? ['40%', '70%'] : '70%',
                        data: data.series || data.distribution || [],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                }
            }
            break

        case 'funnel':
            option = {
                tooltip: { trigger: 'item' },
                legend: {
                    data: (data.series || data.distribution || []).map(item => item.name),
                    type: 'scroll',
                    show: false
                },
                color: data.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
                series: [{
                    name: chart.title,
                    type: 'funnel',
                    left: '10%',
                    top: 60,
                    bottom: 60,
                    width: '80%',
                    sort: 'descending',
                    data: data.series || data.distribution || []
                }]
            }
            break
            
        default:
            // 默认为简单折线图
            option = {
                xAxis: {
                    type: 'category',
                    data: data.xAxis || data.months || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                },
                yAxis: {
                    type: 'value'
                },
                series: data.series || [{
                    data: [150, 230, 224, 218, 135, 147, 260],
                    type: 'line'
                }]
            }
    }
    
    // 设置图表配置
    chartInstance.setOption(option)
    
    // 保存实例引用
    chartInstances.value[index] = chartInstance
    
    // 添加窗口大小变化的自适应
    window.addEventListener('resize', () => {
        chartInstance.resize()
    })
}

// 清理图表实例
onUnmounted(() => {
    chartInstances.value.forEach(instance => {
        if (instance) {
            instance.dispose()
        }
    })
    // 移除所有resize监听器
    window.removeEventListener('resize', () => {})
})
</script>

<style scoped>
.dashboard-viewer-container {
    width: calc(100vw - 400px);
    height: 100%;
    overflow-y: auto;
    background-color: #f5f7fa;
}

.dashboard-header {
    padding: 24px;
    background-color: #fff;
    border-bottom: 1px solid #e4e7ed;
}

.dashboard-title {
    font-size: 24px;
    font-weight: 600;
    color: #1f2f3d;
    margin-bottom: 8px;
}

.dashboard-description {
    color: #666;    

}

.charts-container {
    padding: 20px;
    margin-top: 20px;
}

.chart-card {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    height: 380px;
}

.chart-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

.chart-container {
    height: 320px;
    width: 100%;
}
</style>